from decimal import *
from parsers import constant

PRECISION_DECIMAL = Decimal(10) ** -constant.PRECISION

class Deciplex:
   def __init__(self, real = 0, img = 0):
      self.real = Decimal(real)
      self.img = Decimal(img)

   def __str__(self):
      result = str(self.real.quantize(PRECISION_DECIMAL))
      if self.img >= 0:
         result += '+'
      result += str(self.img.quantize(PRECISION_DECIMAL))
      result += 'i'
      return result

   def __abs__(self):
      return (self.real ** 2 + self.img ** 2).sqrt()

   def sqr_abs(self):
      return self.real ** 2 + self.img ** 2

   def __mul__(self, other):
      result = Deciplex()
      if isinstance(other, Decimal):
         result.real = other * self.real
         result.img = other * self.img
      elif isinstance(other, Deciplex):
         result.real = self.real * other.real - other.img * self.img
         result.img = self.real * other.img + self.img * other.real
      else:
         raise TypeError
      return result

   def __add__(self, other):
      result = Deciplex()
      result.real = self.real + other.real
      result.img = self.img + other.img
      return result

   def __div__(self, other):
      result = Deciplex()
      if isinstance(other, Decimal):
         result.real = self.real / other
         result.img = self.img / other
      return result
